/*
Copyright (C) 2001, 2008 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.data;

import gov.nasa.worldwind.avlist.*;
import gov.nasa.worldwind.formats.tiff.*;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.util.*;

import java.io.IOException;

/**
 * @author dcollins
 * @version $Id: GeotiffRasterReader.java 13194 2010-03-09 16:58:05Z garakl $
 */
public class GeotiffRasterReader extends AbstractDataRasterReader
{
    private static final String[] geotiffMimeTypes = {"image/tiff", "image/geotiff"};
    private static final String[] geotiffSuffixes = {"tif", "tiff", "gtif", "tif.zip", "tiff.zip", "tif.gz", "tiff.gz" };

    public GeotiffRasterReader()
    {
        super(geotiffMimeTypes, geotiffSuffixes);
    }

    protected boolean doCanRead(DataSource source)
    {
        String path = pathFor(source);
        if (path == null)
            return false;

        GeotiffReader reader = null;
        try
        {
            reader = new GeotiffReader(path);
            return reader.isGeotiff( 0 );
        }
        catch (Exception e)
        {
            // Intentionally ignoring exceptions.
            return false;
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
    }

    protected DataRaster[] doRead(DataSource source) throws java.io.IOException
    {
        String path = pathFor(source);
        if (path == null)
        {
            String message = Logging.getMessage("DataRaster.CannotRead", source);
            Logging.logger().severe(message);
            throw new java.io.IOException(message);
        }

        GeotiffReader reader = null;
        DataRaster[] rasters = null;
        try
        {
            reader = new GeotiffReader(path);
            rasters = reader.readDataRaster();
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
        return rasters;
    }

    protected void doReadMetadata(DataSource source, AVList values) throws java.io.IOException
    {
        String path = pathFor(source);
        if (path == null)
        {
            String message = Logging.getMessage("nullValue.PathIsNull", source);
            Logging.logger().severe(message);
            throw new java.io.IOException(message);
        }
        
        GeotiffReader reader = null;
        try
        {
            reader = new GeotiffReader(path);
            reader.copyMetadataTo( values );
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
    }
}
